﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;


namespace advadev.CanOpen
{

    /// <summary>
    /// Represents a network management heartbeat message write transfer
    /// </summary>
    public class NetworkManagementHeartbeatMessageWriteTransfer : ITransfer
    {

        /// <summary>for internal use</summary>
        private bool _isProducerTransfer;
        /// <summary>for internal use</summary>
        private bool _isTransferCompleteAfterSending;
        /// <summary>for internal use</summary>
        private CanOpenMessage _receivedCanOpenMessage;
        /// <summary>for internal use</summary>
        private NetworkManagementHeartbeatMessageReceivedEventHandler _networkManagementHeartbeatMessageReceivedEventHandler;
        /// <summary>for internal use</summary>
        private Collection<CanOpenMessage> _pendingSendMessages = new Collection<CanOpenMessage>();
        /// <summary>for internal use</summary>
        private ReadOnlyCollection<CanOpenMessage> _pendingSendMessagesReference;
        /// <summary>
        /// Default producer COB-ID
        /// </summary>
        static public readonly UInt16 DefaultProducerCobId = 0x700;


        /// <summary>
        /// Initializes a new instance of the
        /// NetworkManagementHeartbeatMessageWriteTransfer class by the given
        /// parameter
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="networkManagementHeartbeatMessageReceivedEventHandler">
        /// Network management heartbeat message received event handler (or null)
        /// </param>
        private NetworkManagementHeartbeatMessageWriteTransfer(CanOpenMessage receivedCanOpenMessage, NetworkManagementHeartbeatMessageReceivedEventHandler networkManagementHeartbeatMessageReceivedEventHandler)
        {
            _isProducerTransfer = false;
            _receivedCanOpenMessage = receivedCanOpenMessage;
            _networkManagementHeartbeatMessageReceivedEventHandler = networkManagementHeartbeatMessageReceivedEventHandler;
        }

        /// <summary>
        /// Initializes a new instance of the
        /// NetworkManagementHeartbeatMessageWriteTransfer class by the given
        /// parameter
        /// </summary>
        /// <param name="networkManagementControlState">
        /// Network management control state to send with the network management
        /// heartbeat message
        /// </param>
        /// <param name="nodeId">
        /// Node id of the device that writes the network management heartbeat
        /// message (must be in the range of 1..127)
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Will be thrown if the node id is not in the range of 1..127
        /// </exception>
        public NetworkManagementHeartbeatMessageWriteTransfer(NetworkManagementControlState networkManagementControlState, byte nodeId)
            : this(networkManagementControlState, nodeId, DefaultProducerCobId)
        {
        }

        /// <summary>
        /// Initializes a new instance of the
        /// NetworkManagementHeartbeatMessageWriteTransfer class by the given
        /// parameter
        /// </summary>
        /// <param name="networkManagementControlState">
        /// Network management control state to send with the network management
        /// heartbeat message
        /// </param>
        /// <param name="nodeId">
        /// Node id of the device that writes the network management heartbeat
        /// message (must be in the range of 1..127)
        /// </param>
        /// <param name="producerCobId">
        /// Producer COB-ID
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Will be thrown if the node id is not in the range of 1..127
        /// </exception>
        public NetworkManagementHeartbeatMessageWriteTransfer(NetworkManagementControlState networkManagementControlState, byte nodeId, UInt16 producerCobId)
        {
            // check parameter
            if (!(1 <= nodeId && nodeId <= 127))
            {
                throw new ArgumentOutOfRangeException("nodeId", "The node id must be in the range of 1..127");
            }

            // initializaton
            _isProducerTransfer = true;
            NodeId = nodeId;
            ProducerCobId = producerCobId;
            NetworkManagementControlState = networkManagementControlState;
        }


        /// <summary>
        /// Gets or sets the node id
        /// </summary>
        private byte NodeId
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the network management control state
        /// </summary>
        private NetworkManagementControlState NetworkManagementControlState
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the producer COB-ID
        /// </summary>
        private UInt16 ProducerCobId
        {
            get;
            set;
        }


        /// <summary>
        /// Checks if the given received can open message is a network
        /// management heartbeat message write transfer request and if so it
        /// returns as out parameter a matching network management heartbeat
        /// message write transfer instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="networkManagementHeartbeatMessageWriteTransfer">
        /// A matching network management heartbeat message write transfer
        /// instance
        /// </param>
        /// <param name="networkManagementHeartbeatMessageReceivedEventHandler">
        /// Network management heartbeat message received event handler (or
        /// null)
        /// </param>
        /// <returns>
        /// True if the received can open message is a network management
        /// heartbeat message write transfer request, false otherwise
        /// </returns>
        static public bool IsNetworkManagementHeartbeatMessageWriteTransfer(CanOpenMessage receivedCanOpenMessage, out NetworkManagementHeartbeatMessageWriteTransfer networkManagementHeartbeatMessageWriteTransfer, NetworkManagementHeartbeatMessageReceivedEventHandler networkManagementHeartbeatMessageReceivedEventHandler)
        {
            return IsNetworkManagementHeartbeatMessageWriteTransfer(receivedCanOpenMessage, out networkManagementHeartbeatMessageWriteTransfer, DefaultProducerCobId, networkManagementHeartbeatMessageReceivedEventHandler);
        }

        /// <summary>
        /// Checks if the given received can open message is a network
        /// management heartbeat message write transfer request and if so it
        /// returns as out parameter a matching network management heartbeat
        /// message write transfer instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="networkManagementHeartbeatMessageWriteTransfer">
        /// A matching network management heartbeat message write transfer
        /// instance
        /// </param>
        /// <param name="producerCobId">
        /// Producer COB-ID
        /// </param>
        /// <param name="networkManagementHeartbeatMessageReceivedEventHandler">
        /// Network management heartbeat message received event handler (or
        /// null)
        /// </param>
        /// <returns>
        /// True if the received can open message is a network management
        /// heartbeat message write transfer request, false otherwise
        /// </returns>
        static public bool IsNetworkManagementHeartbeatMessageWriteTransfer(CanOpenMessage receivedCanOpenMessage, out NetworkManagementHeartbeatMessageWriteTransfer networkManagementHeartbeatMessageWriteTransfer, UInt16 producerCobId, NetworkManagementHeartbeatMessageReceivedEventHandler networkManagementHeartbeatMessageReceivedEventHandler)
        {
            // check parameter
            if (receivedCanOpenMessage == null)
            {
                networkManagementHeartbeatMessageWriteTransfer = null;
                return false;
            }

            // check node id
            UInt16 nodeId = receivedCanOpenMessage.CanId;
            nodeId -= producerCobId;
            if (!(1 <= nodeId && nodeId <= 127))
            {
                networkManagementHeartbeatMessageWriteTransfer = null;
                return false;
            }

            // create transfer instance
            networkManagementHeartbeatMessageWriteTransfer = new NetworkManagementHeartbeatMessageWriteTransfer(receivedCanOpenMessage, networkManagementHeartbeatMessageReceivedEventHandler);
            return true;
        }

        /// <summary>
        /// Starts the producer transfer
        /// </summary>
        private void startProducerTransfer()
        {
            UInt16 canId = ProducerCobId;
            canId += NodeId;
            byte byte0 = (byte)NetworkManagementControlState;
            _pendingSendMessages.Add(new CanOpenMessage(canId, byte0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 1));
            _isTransferCompleteAfterSending = true;
        }

        /// <summary>
        /// Starts the consumer transfer
        /// </summary>
        private void startConsumerTransfer()
        {
            // process data
            if (_networkManagementHeartbeatMessageReceivedEventHandler != null)
            {
                byte controlState = (byte)(_receivedCanOpenMessage.Byte0 & 0x7F);
                NetworkManagementControlState networkManagementControlState = CanOpen.NetworkManagementControlState.Unkown;
                if (controlState == (byte)NetworkManagementControlState.BootUp)
                {
                    networkManagementControlState = NetworkManagementControlState.BootUp;
                }
                else if (controlState == (byte)NetworkManagementControlState.Stopped)
                {
                    networkManagementControlState = NetworkManagementControlState.Stopped;
                }
                else if (controlState == (byte)NetworkManagementControlState.Operational)
                {
                    networkManagementControlState = NetworkManagementControlState.Operational;
                }
                else if (controlState == (byte)NetworkManagementControlState.PreOperational)
                {
                    networkManagementControlState = NetworkManagementControlState.PreOperational;
                }
                _networkManagementHeartbeatMessageReceivedEventHandler(this, new NetworkManagementHeartbeatMessageReceivedEventArgs(networkManagementControlState));
            }

            // end transfer
            TransferComplete = true;
        }


        #region ITransfer implementation
        /// <summary>
        /// Gets a flag indicating whether the transfer is complete (after
        /// sending the pending send messages)
        /// </summary>
        public bool TransferComplete
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the abort code (null for successful transfers)
        /// </summary>
        public CanOpenAbortCode AbortCode
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the pending send messages
        /// </summary>
        public ReadOnlyCollection<CanOpenMessage> PendingSendMessages
        {
            get
            {
                if (_pendingSendMessagesReference == null)
                {
                    _pendingSendMessagesReference = new ReadOnlyCollection<CanOpenMessage>(_pendingSendMessages);
                }
                return _pendingSendMessagesReference;
            }
        }


        /// <summary>
        /// Starts the transfer
        /// </summary>
        public void Start()
        {
            if (_isProducerTransfer)
            {
                startProducerTransfer();
            }
            else
            {
                startConsumerTransfer();
            }
        }

        /// <summary>
        /// Times out the transfer
        /// </summary>
        public void TimeOut()
        {
            AbortCode = new CanOpenAbortCode(0x00, 0x00, 0x04, 0x05);
        }

        /// <summary>
        /// Finalizes the transfer
        /// </summary>
        public void FinalizeTransfer()
        {
        }

        /// <summary>
        /// Continues the transfer after sending messages
        /// </summary>
        public void ContinueAfterSendingMessages()
        {
            _pendingSendMessages.Clear();
            if (_isTransferCompleteAfterSending)
            {
                TransferComplete = true;
            }
        }

        /// <summary>
        /// Processes the received message
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <returns>
        /// True, if the given can open message was related to this transfer,
        /// false otherwise
        /// </returns>
        public bool ProcessReceivedMessage(CanOpenMessage receivedCanOpenMessage)
        {
            return false;
        }
        #endregion ITransfer implementation

    }

}
